<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
      <!-- 提示 -->
      <!-- <el-alert title="添加商品信息" type="info" center show-icon :closable="false"></el-alert> -->
      <!-- 步骤条 -->
      <!-- <el-steps :space="200" :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="sku信息"></el-step>
        <el-step title="完成"></el-step>
      </el-steps> -->

      <!-- Tab栏 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        label-position="top"
      >
        <el-tabs
          v-model="activeIndex"
          :tab-position="'top'"
          :before-leave="beforeTabLeave"
          @tab-click="tabClicked"
        >
          <el-tab-pane label="基本信息" name="0">
           <el-form-item label="商品名称" prop="spuName">
              <el-input v-model="addForm.spuName"></el-input>
            </el-form-item>
            <el-form-item label="商品描述" prop="spuDescription">
              <el-input v-model="addForm.spuDescription"></el-input>
            </el-form-item>
            <el-form-item label="价格" prop="price">
              <el-input v-model="addForm.price"></el-input>
            </el-form-item>
            <el-form-item label="重量(kg)" prop="weight">
              <el-input v-model="addForm.weight"></el-input>
            </el-form-item>
            <el-form-item label="库存" prop="stockCount">
              <el-input  v-model="addForm.stockCount"></el-input>
            </el-form-item> 
            <!-- <el-form-item label="是否有sku" prop="isSku">
              <el-switch
                v-model="addForm.isSku"
                :active-value="1"
                :inactive-value="0"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="是"
                inactive-text="否"
              ></el-switch>
            </el-form-item>  -->
            <el-form-item label="商品分类" prop="catalogId">
              <el-cascader
               ref="cascader"
                v-model="addForm.catalogId"
                :options="cateList"
                :props="cascaderProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
            <el-form-item label="选择品牌" prop="brandId">
              <el-select v-model="addForm.brandId" placeholder="请选择">
                <el-option
                  v-for="(item,i) in brands"
                  :key="i"
                  :label="item.brandName"
                  :value="item.brandId">
                </el-option>
              </el-select>
            </el-form-item>
            <el-button type="success" @click="jump('1')">下一步：上传图片</el-button>
          </el-tab-pane>
           <el-tab-pane label="商品图片" name="1">
             <el-card class="box-card" style="width:80%;margin:20px auto">
              <el-form-item label="商品图集" prop="images">
                <OssUploads v-model="images" ref="OssUploads1"></OssUploads>
              </el-form-item>
              <el-form-item label="商品介绍" prop="decript">
                <OssUploads v-model="decript" ref="OssUploads2"></OssUploads>
              </el-form-item>
              <div style="margin:auto">
                <el-button type="primary" @click="jump('0')">上一步</el-button>
                <el-button type="success" @click="jump('2')">下一步：设置商品属性</el-button>
              </div>
            </el-card>
          </el-tab-pane>
           <el-tab-pane label="商品属性" name="2">
             <el-card class="box-card" style="width:80%;margin:20px auto">
              <el-tabs tab-position="left" style="width:98%">
                <el-tab-pane
                  :label="group.attrGroupName"
                  v-for="(group,gidx) in dataResp.attrGroups"
                  :key="group.attrGroupId"
                >
                  <!-- 遍历属性,每个tab-pane对应一个表单，每个属性是一个表单项  baseAttrs[0] = [{attrId:xx,val:}]-->
                  <el-form ref="form" :model="addForm">
                    <el-form-item
                      :label="attr.attrName"
                      v-for="(attr,aidx) in group.attrs"
                      :key="attr.attrId"
                    >
                      <el-input
                        v-model="dataResp.baseAttrs[gidx][aidx].attrId"
                        type="hidden"
                        v-show="true"
                      ></el-input>
                      <el-select
                        v-model="dataResp.baseAttrs[gidx][aidx].attrValue"
                        :multiple="attr.valueType == 1"
                        filterable
                        allow-create
                        default-first-option
                        placeholder="请选择或输入"
                      >
                        <el-option
                          v-for="(val,vidx) in attr.valueSelect.split('，')"
                          :key="vidx"
                          :label="val"
                          :value="val"
                        ></el-option>
                      </el-select>
                      <!-- <el-checkbox
                        v-model="dataResp.baseAttr[gidx][aidx].showDesc"
                        :true-label="1"
                        :false-label="0"
                      >快速展示</el-checkbox> -->
                    </el-form-item>
                  </el-form>
                </el-tab-pane>
              </el-tabs>
              <div style="margin:auto">
                <el-button type="primary" @click="jump('1')">上一步</el-button>
                <el-button type="success" @click="jump('3')">下一步：设置商品参数</el-button>
              </div>
            </el-card>
            <!-- <el-form-item :label="item.attrName" v-for="item in addForm.baseAttrs" :key="item.attrId">
              <el-input v-model="item.valueSelect"></el-input>
            </el-form-item> -->
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="3">
            <el-card class="box-card" style="width:80%;margin:20px auto">
              <el-card class="box-card">
                <div slot="header" class="clearfix">
                  <span>选择商品参数</span>
                  <el-form ref="saleform" :model="addForm">
                    <el-form-item
                      :label="attr.attrName"
                      v-for="(attr,aidx) in dataResp.saleAttrs"
                      :key="attr.attrId"
                    >
                      <el-input
                        v-model="dataResp.tempSaleAttrs[aidx].attrId"
                        type="hidden"
                        v-show="false"
                      ></el-input>
                      <el-checkbox-group v-model="dataResp.tempSaleAttrs[aidx].attrValues">
                        <el-checkbox
                          :label="val"
                          v-for="val in attr.valueSelect.split('，')"
                          :key="val"
                        ></el-checkbox>
                        <div style="margin-left:20px;display:inline">
                          <el-button
                            v-show="!inputVisible[aidx].view"
                            class="button-new-tag"
                            size="mini"
                            @click="showInput(aidx)"
                          >+自定义</el-button>
                          <el-input
                            v-show="inputVisible[aidx].view"
                            v-model="inputValue[aidx].val"
                            :ref="'saveTagInput'+aidx"
                            size="mini"
                            style="width:150px"
                            @keyup.enter.native="handleInputConfirm(aidx)"
                            @blur="handleInputConfirm(aidx)"
                          ></el-input>
                        </div>
                      </el-checkbox-group>
                    </el-form-item>
                  </el-form>
                </div>
                <el-button type="primary" @click="jump('2')">上一步</el-button>
                <el-button type="success" @click="jump('4')">下一步 设置sku信息</el-button>
              </el-card>
            </el-card>
          </el-tab-pane>
          <el-tab-pane label="sku信息" name="4">
            <el-card class="box-card" style="width:100%;margin:20px auto">
          <el-table :data="addForm.skus" style="width: 100%">
            <el-table-column label="属性组合">
              <el-table-column
                :label="item.attrName"
                v-for="(item,index) in dataResp.tableAttrColumn"
                :key="item.attrId"
              >
                <template slot-scope="scope">
                  <span style="margin-left: 10px">{{ scope.row.attr[index].attrValue }}</span>
                </template>
              </el-table-column>
            </el-table-column>
            <el-table-column label="商品名称" prop="skuName">
              <template slot-scope="scope">
                <el-input v-model="scope.row.skuName"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="标题" prop="skuTitle">
              <template slot-scope="scope">
                <el-input v-model="scope.row.skuTitle"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="副标题" prop="skuSubtitle">
              <template slot-scope="scope">
                <el-input v-model="scope.row.skuSubtitle"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="商品价格" prop="price">
              <template slot-scope="scope">
                <el-input v-model="scope.row.price"></el-input>
              </template>
            </el-table-column>
            <el-table-column
                prop="stockCount"
                label="商品库存"
                width="100">
                <template slot-scope="scope">
                  <el-input v-model="scope.row.stockCount"></el-input>
                </template>
              </el-table-column>
              <el-table-column
                prop="weight"
                label="商品重量(kg)"
                width="150">
                 <template slot-scope="scope">
                  <el-input v-model="scope.row.weight"></el-input>
                </template>
              </el-table-column>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-row>
                  <el-col :span="24">
                    <label style="display:block;float:left">选择图集 </label>
                    <OssUploads ref="OssUploads2" style="float:left;margin-left:10px;" v-model="uploadImages"></OssUploads>
                    
                  </el-col>
                  <el-col :span="24">
                    <el-divider></el-divider>
                  </el-col>
                  <el-col :span="24">
                    <el-card
                      style="width:170px;float:left;margin-left:15px;margin-top:15px;"
                      :body-style="{ padding: '0px' }"
                      v-for="(img,index) in addForm.images"
                      :key="index"
                    >
                      <img :src="img" style="width:150px;height:170px" />
                      <div style="padding: 14px;">
                        <el-row>
                          <el-col :span="12">
                            <el-checkbox
                              v-model="scope.row.images[index].imgUrl"
                              :true-label="img"
                              false-label
                              :checked=true
                            ></el-checkbox>
                           <!-- {{scope.row}} -->
                          </el-col>
                          <el-col :span="12">
                            <el-tag v-if="scope.row.images[index].defaultImg == 1">
                              <input
                                type="radio"
                                checked
                                :name="scope.row.skuName"
                                @change="checkDefaultImg(scope.row,index,img)"
                              />设为默认
                            </el-tag>
                            <el-tag v-else>
                              <input
                                type="radio"
                                :name="scope.row.skuName"
                                @change="checkDefaultImg(scope.row,index,img)"
                              />设为默认
                            </el-tag>
                          </el-col>
                        </el-row>
                      </div>
                    </el-card>
                  </el-col>
                </el-row>
              </template>
            </el-table-column>
          </el-table>
          <el-button type="primary" @click="jump('3')">上一步</el-button>
          <el-button type="success"  @click="addGoods">下一步：保存商品信息 </el-button>
        </el-card>
        </el-tab-pane>
          <el-tab-pane label="完成" name="5">
            <h1>添加成功</h1>
            <el-button type="primary" @click="addAgian">继续添加</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import _ from 'lodash'
import OssUploads from '../upload/OssUploads.vue'
export default {
  data () {
    return {
      // 步骤条默认激活 与左侧Tab联动
      activeIndex: '0',
      // 添加商品的表单对象
      addForm: {
        spuName:"",
        spuDescription:"",
        brandId:'',
        catalogId:'',
        weight:'',
        price:'',
        isSku:1,
        createTime:'',
        // 商品所属分类数组
        images:[],
        // 商品详情描述
        decript:[],
        // 规格参数数据
        baseAttrs:[],
        skus:[],
        stockCount:'',
        publishStatus:1
      },
      addFormRules: {
        spuName: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        spuDescription: [
          { required: true, message: '请输入商品描述', trigger: 'blur' }
        ],
        brandId: [
          { required: true, message: '请选择商品品牌', trigger: 'blur' }
        ],
        catalogId: [
          { required: true, message: '请输入商品分类', trigger: 'blur' }
        ],
        images: [
          { required: true, message: '请添加商品图集', trigger: 'blur' }
        ],
        decript: [
          { required: true, message: '请添加商品详情', trigger: 'blur' }
        ],
        decript: [
          { required: true, message: '请添加商品介绍图片', trigger: 'blur' }
        ],
         weight:[{ required: true, message: '请输入商品重量', trigger: 'blur' }],
        price:[{ required: true, message: '请输入商品的最低价格', trigger: 'blur' }],
        stockCount:[{ required: true, message: '请输入商品库存', trigger: 'blur' }],
       isSku:[{ required: true, message: '请选择是否有sku参数', trigger: 'blur' }],
      },
      // 商品参数
      attrs:[],
      skuData:{
       attrs:[],
       skuName: "",
       price: '',
       skuTitle: "",
       descar: "",
       weight: "",
       stockCount: ''
      },
      decript:[],
      images:[],
      // 商品列表
      cateList: [],
      // 级联选择器配置
      cascaderProps: {
        expandTrigger: 'hover',
        label: 'catName',
        value: 'catId',
        children: 'children'
      },
      brands:[],
      baseAttrs: [],
      // ????
      dataResp: {
        //后台返回的所有数据
        attrGroups: [],
        baseAttrs: [],
        saleAttrs: [],
        tempSaleAttrs: [],
        tableAttrColumn: [],
        memberLevels: [],
        steped: [false, false, false, false, false]
      },
      uploadImages: [],
      inputVisible: [],
      inputValue: []
    }
  },
  components:{
    OssUploads
  },
  created () {
    this.getCateList()
    this.images = [],
      this.decript = []
  },
  // 监听属性值的改变，进而改变sku商品名
  watch:{
    uploadImages(val) {
      var images = []
      val.forEach(item =>{
        images.push(item.url) 
      })
      let imgArr =  Array.from(new Set(this.addForm.images.concat(images)));
     
      this.addForm.skus.forEach((item, index) => {
        // console.log(item.images.length)
        let len = imgArr.length - this.addForm.skus[index].images.length; //还差这么多
         console.log("len", len);
        if (len > 0) {
          let imgs = new Array(len);
          imgs = imgs.fill({ imgUrl: "", defaultImg: 0 });
          this.addForm.skus[index].images = item.images.concat(imgs);
        }
      });
      this.addForm.images = imgArr; //去重
      // console.log("this.addForm.skus", this.addForm.skus);
      // console.log("this.addForm", this.addForm);
    },
    images: {
      handler(newName, oldName) {
        const goodsImages=[]
        newName.forEach(item =>{
          goodsImages.push(item.url)  
        })
        this.addForm.images =  goodsImages
        //  console.log("我在监听",this.addForm.images)
    },
    deep: true,
    immediate: true
    },
    decript: {
      handler(newName, oldName) {
        const goodsDecript=[]
        newName.forEach(item =>{
          goodsDecript.push(item.url)  
        })
        this.addForm.decript =  goodsDecript
      // console.log(this.addForm.decript)
    },
    deep: true,
    immediate: true
    }
  },
  computed: {
    getCateId () {
      return this.addForm.catalogId
    }
  },
  methods: {
    // 获取分类
    async  getCateList(){
        const {data:res} = await this.$http.get("/xuanmall/category/list/tree")
        if(res.code === 0){
         this.cateList = this.formatData(res.data)
        }
      },
     // 格式化数据，递归将空的children置为undefined
    formatData(data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          data[i].children = undefined
        } else {
          this.formatData(data[i].children)
        }
      }
      return data
      },
      // 获取所有品牌
    async  getBrands(){
      const {data:res} = await this.$http.get(`/xuanmall/categorybrandrelation/brands/list?catId=${this.addForm.catalogId}`)
      console.log(res)
      this.brands = res.data
    },
    // 级联选择器选中项变化时触发
    handleChange () {
      this.brands = []
      var nodeInfo = this.$refs.cascader.getCheckedNodes()
      // console.log(nodeInfo)
      this.addForm.catalogId = nodeInfo[0].data.catId;
      this.getBrands()
    },
    beforeTabLeave (activeName, odlActiveName) {
      // 未选中商品分类阻止Tab标签跳转
      if (odlActiveName === '0' && this.addForm.catalogId === '') {
        this.$message.error('请先选择商品分类')
        return false
      }
    },
     // 继续添加
    addAgian() {
      this.activeIndex = '0';
      this.clearSpuData();
    },
    clearSpuData() {
      this.images = []
      this.decript=[]
       this.$refs.OssUploads1.$refs.upload.clearFiles()
       this.$refs.OssUploads2.$refs.upload.clearFiles()
      this.addForm = {
        spuName: "",
        spuDescription: "",
        catalogId: 0,
        brandId: "",
        decript: [], 
        images: [], 
        baseAttrs: [], 
        skus: []
      };
    },
    // 点击下一步跳转
    jump(value){
      this.activeIndex = value
      this.tabClicked()
    },
    // Tab标签被选中时触发
    async tabClicked () {
      // 访问动态参数面板
      if (this.activeIndex === '3') {
        //把页面绑定的所有attr处理到spu里面,这一步都要做
        this.addForm.baseAttrs = [];
        this.dataResp.baseAttrs.forEach(item => {
          item.forEach(attr => {
            let { attrId, attrValue, showDesc } = attr;
            //跳过没有录入值的属性
            if (attrValue != "" && showDesc != '') {
              if (attrValue instanceof Array) {
                //多个值用,隔开
                attrValue = attrValue.join("，");
              }
              this.addForm.baseAttrs.push({ attrId, attrValue, showDesc });
              console.log("this.addForm.baseAttrs",this.addForm.baseAttrs)
            }
          });
        });
        // console.log("baseAttrs", this.addForm.baseAttrs);
        // 获取参数信息
        const { data: res } = await this.$http.get(`xuanmall/attr/sale/list/${this.getCateId}`)
        if (res.code !== 0) {
          return this.$message.error('获取商品参数列表失败！')
        }
        this.dataResp.saleAttrs = res.page.list;
          res.page.list.forEach(item => {
            this.dataResp.tempSaleAttrs.push({
              attrId: item.attrId,
              attrValues: [],
              attrName: item.attrName
            });
            this.inputVisible.push({ view: false });
            this.inputValue.push({ val: "" });
          });
      } else if (this.activeIndex === '2') {
        // console.log("ss",this.addForm.images)
        const { data: res } = await this.$http.get(`/xuanmall/attrgroup/${this.getCateId}/withattr`)
         console.log("res",res)
        if (res.code !== 0) {
          return this.$message.error('获取商品属性列表失败！')
        }
        // this.addForm.baseAttrs  = [],
        res.data.forEach(item => {
           let attrArray = [];
          if(item.attrs.length){
            item.attrs.forEach(attr => {
              attrArray.push({
                attrId: attr.attrId,
                attrValue: "",
                showDesc: attr.showDesc
              });
          }) ;
          this.dataResp.baseAttrs.push(attrArray);
          }
        });
         console.log("baseAttrs",  this.dataResp.baseAttrs)
          this.dataResp.attrGroups = res.data;
      }
      else if(this.activeIndex === '4'){
        //根据笛卡尔积运算进行生成sku
        let selectValues = [];
        this.dataResp.tableAttrColumn = [];
        this.dataResp.tempSaleAttrs.forEach(item => {
          if (item.attrValues.length > 0) {
            selectValues.push(item.attrValues);
            this.dataResp.tableAttrColumn.push(item);
          }
        });
        let descartes = this.descartes(selectValues);
        // console.log("生成的组合", JSON.stringify(descartes));
        //有多少descartes就有多少sku
        let skus = [];
        descartes.forEach((descar, descaridx) => {
          let attrArray = []; //sku属性组
          descar.forEach((de, index) => {
            //构造saleAttr信息
            let saleAttrItem = {
              attrId: this.dataResp.tableAttrColumn[index].attrId,
              attrName: this.dataResp.tableAttrColumn[index].attrName,
              attrValue: de
            };
            attrArray.push(saleAttrItem);
          });
          //先初始化几个images，后面的上传还要加
          let imgs = [];
          this.addForm.images.forEach((img, idx) => {
            imgs.push({ imgUrl: img, defaultImg: idx === 0?1 :1 });
          });
          //;descaridx，判断如果之前有就用之前的值;
          // let res = this.hasAndReturnSku(this.addForm.skus, descar);
          // console.log("descar",descar)
          // if (res === null) {
            skus.push({
              attr: attrArray,
              skuName: this.addForm.spuName + " " + descar.join(' '),
              price: this.addForm.price,
              skuTitle: this.addForm.spuName + " " + descar.join(' '),
              skuSubtitle: this.addForm.spuDescription,
              images: imgs,
              stockCount: this.addForm.stockCount,
              weight:this.addForm.weight,
            });
          // } else {
          //   skus.push(res);
          // }
        });
        this.addForm.skus = skus;
        console.log("结果!!!", this.addForm.skus, this.dataResp.tableAttrColumn);
      }
    },
    //判断如果包含之前的sku的descar组合，就返回这个sku的详细信息；
    // hasAndReturnSku(skus, descar) {
    //   let res = null;
    //   if (skus.length > 0) {
    //     for (let i = 0; i < skus.length; i++) {
    //       if (skus[i].descar.join(" ") == descar.join(" ")) {
    //         res = skus[i];
    //       }
    //     }
    //   }
    //   return res;
    // },
    // 显示输入框
    showInput(idx) {
      this.inputVisible[idx].view = true;
    },
     checkDefaultImg(row, index, img) {
      //这个图片被选中了，
      row.images[index].imgUrl = img; //默认选中
      row.images[index].defaultImg = 1; //修改标志位;
      //修改其他人的标志位
      row.images.forEach((item, idx) => {
        if (idx != index) {
          row.images[idx].defaultImg = 0;
        }
      });
    },
    // 输入框失去焦点
    handleInputConfirm(idx) {
      let inputValue = this.inputValue[idx].val;
      if (inputValue) {
        // this.dynamicTags.push(inputValue);
        if (this.dataResp.saleAttrs[idx].valueSelect === "") {
          this.dataResp.saleAttrs[idx].valueSelect = inputValue;
        } else {
          this.dataResp.saleAttrs[idx].valueSelect += "，" + inputValue;
        }
      }
      this.inputVisible[idx].view = false;
      this.inputValue[idx].val = "";
    },
    async  addGoods () {
      this.addForm.createTime = new Date().getTime()
      console.log("最后添加的商品",this.addForm)
      // 发送请求
      const {data:res} = await this.$http.post('/xuanmall/spumessage/save',this.addForm)
      console.log(res)
      if(res.code !== 0){
        this.$message.error("保存失败")
        return 0
      }
      this.$message.success("保存成功")
      this.addForm.images= []
      this.addForm.decript=[]
      this.dataResp= {
        //后台返回的所有数据
        attrGroups: [],
        baseAttrs: [],
        saleAttrs: [],
        tempSaleAttrs: [],
        tableAttrColumn: [],
        memberLevels: [],
        steped: [false, false, false, false, false]
      },
      this.jump('5')
    },
     //笛卡尔积运算
    descartes(list) {
      //parent上一级索引;count指针计数
      var point = {};
      var result = [];
      var pIndex = null;
      var tempCount = 0;
      var temp = [];
      //根据参数列生成指针对象
      for (var index in list) {
        if (typeof list[index] == "object") {
          point[index] = { parent: pIndex, count: 0 };
          pIndex = index;
        }
      }
      //单维度数据结构直接返回
      if (pIndex == null) {
        return list;
      }
      //动态生成笛卡尔积
      while (true) {
        for (var index in list) {
          tempCount = point[index]["count"];
          temp.push(list[index][tempCount]);
        }

        //压入结果数组
        result.push(temp);
        temp = [];

        //检查指针最大值问题
        while (true) {
          if (point[index]["count"] + 1 >= list[index].length) {
            point[index]["count"] = 0;
            pIndex = point[index]["parent"];
            if (pIndex == null) {
              return result;
            }

            //赋值parent进行再次检查
            index = pIndex;
          } else {
            point[index]["count"]++;
            break;
          }
        }
      }
    }
  }
}
</script>

<style lang='less' scoped>
.el-checkbox {
  margin: 0 8px 0 0 !important;
}
.previewImg{
  width: 100%;
}
.btnAdd{
  margin-top: 15px
}
</style>
